package com.changgou.controller;

import com.changgou.entity.FastDFSFile;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.util.FastDFSUtils;
import org.csource.common.MyException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件操作控制器
 *
 * @author gaofeng
 * @date 2025年04月19日 14:45
 */
@RestController
@RequestMapping(value = "/file")
public class FileController {
    @PostMapping(value = "/upload")
    public Result upload(@RequestBody MultipartFile file) throws IOException, MyException {
        String url = FastDFSUtils.upload(createFastDFSFile(file));
        return new Result<>(true, StatusCode.OK, "上传成功", url);
    }

    private FastDFSFile createFastDFSFile(MultipartFile file) throws IOException {
        FastDFSFile fastDFSFile = new FastDFSFile();
        fastDFSFile.setName(file.getOriginalFilename());
        fastDFSFile.setContent(file.getBytes());
        fastDFSFile.setExt(StringUtils.getFilenameExtension(file.getOriginalFilename()));
        return fastDFSFile;
    }
}
